package com.Java.train.business.service.Impl;

import cn.hutool.core.date.DateTime;
import com.Java.train.business.entity.ConfirmOrder;
import com.Java.train.business.entity.DTO.ConfirmOrderTicketDTO;
import com.Java.train.business.entity.DailyTrainSeat;
import com.Java.train.business.entity.DailyTrainTicket;
import com.Java.train.business.enums.ConfirmOrderStatusEnum;
import com.Java.train.business.feign.MemberTicketFeign;
import com.Java.train.business.mapper.ConfirmOrderMapper;
import com.Java.train.business.mapper.cust.DailyTrainTicketMapperCust;
import com.Java.train.business.service.ConfirmOrderService;
import com.Java.train.business.service.daily.DailyTrainSeatService;
import com.Java.train.business.service.daily.DailyTrainTicketService;
import com.Java.train.common.context.LoginMemberContext;
import com.Java.train.common.req.MemberTicketReq;
import com.Java.train.common.response.CommonResp;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
//import io.seata.core.context.RootContext;
//import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.renderable.RenderContext;
import java.util.Date;
import java.util.List;

@Service
public class AfterDoConfirm {
    private static final Logger LOG = LoggerFactory.getLogger(AfterDoConfirm.class);
    @Resource
    private DailyTrainSeatService dailyTrainSeatService;
    @Resource
    private DailyTrainTicketService dailyTrainTicketService;
    @Resource
    DailyTrainTicketMapperCust dailyTrainTicketMapperCust;
    @Resource
    MemberTicketFeign memberTicketFeign;
    @Resource
    ConfirmOrderMapper confirmOrderMapper;


    //    @Transactional
//    @GlobalTransactional
    public void afterDofirm(DailyTrainTicket dailyTrainTicket, List<DailyTrainSeat> finalSeatList,
                            List<ConfirmOrderTicketDTO> tickets, ConfirmOrder confirmOrder) throws Exception {
//        LOG.info("seata全局事务ID为：{}", RootContext.getXID());
        // 1.更改车票本身数据
        DateTime now = DateTime.now();
        for (int t = 0; t < tickets.size(); t++) {
            DailyTrainSeat dailyTrainSeat = finalSeatList.get(t);
//            LambdaUpdateWrapper<DailyTrainSeat> wrapper = new LambdaUpdateWrapper<>();
            dailyTrainSeat.setUpdateTime(now);
            dailyTrainSeatService.updateById(dailyTrainSeat);


            // 2.更改该车票影响其他站点车票的数量（该车程经过站点区间从起始与终点站向两侧，只要有部分或全部包含该车票车程的区间车票都应减少，直到有其他车票影响过位置)
            Integer startIndex = dailyTrainTicket.getStartIndex();
            Integer endIndex = dailyTrainTicket.getEndIndex();
            char[] aChars = dailyTrainSeat.getSell().toCharArray();
            Integer minEndIndex = startIndex + 1;
            Integer maxStartIndex = endIndex - 1;

            Integer minStartIndex = 0;
            // 2.1获取最小起始站点（遇到1，即其他买过的车票为止）
            for(int i = startIndex - 1; i >= 0; i--){
                if(aChars[i] == '1'){
                    minStartIndex = i + 1;
                    break;
                }
            }
            LOG.info("影响出发站区间：" + minStartIndex + "-" + maxStartIndex);
            // 2.2获取最大终止点
            Integer maxEndIndex = dailyTrainSeat.getSell().length();
            for(int j = endIndex; j < dailyTrainSeat.getSell().length(); j++){
                if(aChars[j] == '1'){
                    maxEndIndex = j;
                    break;
                }
            }

            LOG.info("影响到达站区间：" + minEndIndex + "-" + maxEndIndex);

            long start1 = System.currentTimeMillis();
            // 3.1 修改座位sell信息，扣减余票信息中的数量 动态sql，将在这区间内的所有的车站余票总数进行削减
            dailyTrainTicketMapperCust.updateCountBySell(dailyTrainSeat.getDate(),
                    dailyTrainSeat.getTrainCode(),
                    dailyTrainSeat.getSeatType(),
                    minStartIndex,
                    maxStartIndex,
                    minEndIndex,
                    maxEndIndex);
            long end1 = System.currentTimeMillis();
            LOG.info("动态扣减区间内sell的时间为：{}", end1 - start1);

            // 3.2为用户增添订单信息
            long start2 = System.currentTimeMillis();
            MemberTicketReq memberTicketReq = new MemberTicketReq();
            ConfirmOrderTicketDTO ticketDTO = tickets.get(t);
            memberTicketReq.setMemberId(confirmOrder.getMemberId());
            memberTicketReq.setPassengerId(ticketDTO.getPassengerId());
            memberTicketReq.setPassengerName(ticketDTO.getPassengerName());
            memberTicketReq.setTrainDate(dailyTrainSeat.getDate());
            memberTicketReq.setTrainCode(dailyTrainSeat.getTrainCode());
            memberTicketReq.setCarriageIndex(dailyTrainSeat.getCarriageIndex());
            memberTicketReq.setSeatRow(dailyTrainSeat.getLine());
            memberTicketReq.setSeatCol(dailyTrainSeat.getCol());
            memberTicketReq.setStartStation(dailyTrainTicket.getStart());
            memberTicketReq.setEndStation(dailyTrainTicket.getEnd());
            memberTicketReq.setStartTime(dailyTrainTicket.getStartTime());
            memberTicketReq.setEndTime(dailyTrainTicket.getEndTime());
            memberTicketReq.setSeatType(dailyTrainSeat.getSeatType());
            memberTicketFeign.modify(memberTicketReq);
            long end2 = System.currentTimeMillis();
            LOG.info("跨服务为用户增添订单信息的时间为：{}", end2 - start2);

            // 3.3 更改订单状态
            confirmOrder.setUpdateTime(now);
            confirmOrder.setStatus(ConfirmOrderStatusEnum.SUCCESS.getCode());
            confirmOrderMapper.updateById(confirmOrder);
//            Thread.sleep(2000);
//            if(1 == 1){
//                throw new Exception("假装犯错捏");
//            }

            // 4.修改订单状态


//        for (int j = 0; j < finalSeatList.size(); j++) {
//            DailyTrainSeat dailyTrainSeat = finalSeatList.get(j);
//            DailyTrainSeat seatForUpdate = new DailyTrainSeat();
//            seatForUpdate.setId(dailyTrainSeat.getId());
//            seatForUpdate.setSell(dailyTrainSeat.getSell());
//            seatForUpdate.setUpdateTime(new Date());
//            LambdaUpdateWrapper<DailyTrainSeat> wrapper = new LambdaUpdateWrapper<>();
//            dailyTrainSeatService.updateById(dailyTrainSeat);
//
//            // 计算这个站卖出去后，影响了哪些站的余票库存
//            // 参照2-3节 如何保证不超卖、不少卖，还要能承受极高的并发 10:30左右
//            // 影响的库存：本次选座之前没卖过票的，和本次购买的区间有交集的区间
//            // 假设10个站，本次买4~7站
//            // 原售：001000001
//            // 购买：000011100
//            // 新售：001011101
//            // 影响：XXX11111X
//            // Integer startIndex = 4;
//            // Integer endIndex = 7;
//            // Integer minStartIndex = startIndex - 往前碰到的最后一个0;
//            // Integer maxStartIndex = endIndex - 1;
//            // Integer minEndIndex = startIndex + 1;
//            // Integer maxEndIndex = endIndex + 往后碰到的最后一个0;
//            Integer startIndex = dailyTrainTicket.getStartIndex();
//            Integer endIndex = dailyTrainTicket.getEndIndex();
//            char[] chars = seatForUpdate.getSell().toCharArray();
//            Integer maxStartIndex = endIndex - 1;
//            Integer minEndIndex = startIndex + 1;
//            Integer minStartIndex = 0;
//            for (int i = startIndex - 1; i >= 0; i--) {
//                char aChar = chars[i];
//                if (aChar == '1') {
//                    minStartIndex = i + 1;
//                    break;
//                }
//            }
//            LOG.info("影响出发站区间：" + minStartIndex + "-" + maxStartIndex);
//
//            Integer maxEndIndex = seatForUpdate.getSell().length();
//            for (int i = endIndex; i < seatForUpdate.getSell().length(); i++) {
//                char aChar = chars[i];
//                if (aChar == '1') {
//                    maxEndIndex = i;
//                    break;
//                }
//            }
//            LOG.info("影响到达站区间：" + minEndIndex + "-" + maxEndIndex);
//
//            dailyTrainTicketMapperCust.updateCountBySell(
//                    dailyTrainSeat.getDate(),
//                    dailyTrainSeat.getTrainCode(),
//                    dailyTrainSeat.getSeatType(),
//                    minStartIndex,
//                    maxStartIndex,
//                    minEndIndex,
//                    maxEndIndex);
//
//            // 调用会员服务接口，为会员增加一张车票
//            MemberTicketReq memberTicketReq = new MemberTicketReq();
//            memberTicketReq.setMemberId(confirmOrder.getMemberId());
//            memberTicketReq.setPassengerId(tickets.get(j).getPassengerId());
//            memberTicketReq.setPassengerName(tickets.get(j).getPassengerName());
//            memberTicketReq.setTrainDate(dailyTrainTicket.getDate());
//            memberTicketReq.setTrainCode(dailyTrainTicket.getTrainCode());
//            memberTicketReq.setCarriageIndex(dailyTrainSeat.getCarriageIndex());
//            memberTicketReq.setSeatRow(dailyTrainSeat.getLine());
//            memberTicketReq.setSeatCol(dailyTrainSeat.getCol());
//            memberTicketReq.setStartStation(dailyTrainTicket.getStart());
//            memberTicketReq.setStartTime(dailyTrainTicket.getStartTime());
//            memberTicketReq.setEndStation(dailyTrainTicket.getEnd());
//            memberTicketReq.setEndTime(dailyTrainTicket.getEndTime());
//            memberTicketReq.setSeatType(dailyTrainSeat.getSeatType());
//            CommonResp<Object> commonResp = memberTicketFeign.modify(memberTicketReq);
//            LOG.info("调用member接口，返回：{}", commonResp);
//
//            // 更新订单状态为成功
//            ConfirmOrder confirmOrderForUpdate = new ConfirmOrder();
//            confirmOrderForUpdate.setId(confirmOrder.getId());
//            confirmOrderForUpdate.setUpdateTime(new Date());
//            confirmOrderForUpdate.setStatus(ConfirmOrderStatusEnum.SUCCESS.getCode());
//            confirmOrderMapper.updateById(confirmOrder);

        }
    }
}

